﻿Imports System.IO
Imports System.Xml
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Imports System.ComponentModel
Imports System.Configuration

Public Class Form1
    Private ReadOnly key() As Byte = _
{1, 2, 3, 56, 5, 6, 36, 8, 9, 10, 11, 12, 63, 14, _
15, 49, 44, 65, 19, 84, 21, 22, 28, 24}
    Private ReadOnly iv() As Byte = {1, 2, 45, 3, 22, 7, 84, 1}

    ' instantiate the class with the arrays
    Private des As New TripleDES(key, iv)

    Public UserLevel As Integer
    Public UserName As String
    Public Password As String 'encrypted already

    Public ArmaVersion As String = "ARMA"

    Dim Version As String = "1.3.6.0"

    'Public oWS As New ArmAManager.ArmaWebService()
    Public oWS As New com.teamduck.arma.ArmaWebService

    Public Server As Integer = 1
    Dim SettingsFile As String = Application.LocalUserAppDataPath & "\ServerSettings.xml"

    Public dtServerList As New DataSet
    Public ds As New DataSet

    Public FileLocation As String = Application.LocalUserAppDataPath & "\servers.xml"

    'whether it is currently connected to a server
    Public boolConnected As Boolean = False
    Dim strike As Integer = 0

    Dim dtMissionsList As New DataTable

    'File Upload Info
    Dim frmUpload As New frmUploading


    Public receivingUdpClient As UdpClient
    Public RemoteIpEndPoint As New  _
          System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
    Public ThreadReceive As System.Threading.Thread
    Dim SocketNO As Integer


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        PictureBox1.Image = Nothing

        Dim f As New frmUpdates
        f.RichTextBox1.Text = My.Computer.FileSystem.ReadAllText("ReadMe.txt")
        f.ShowDialog()

        GetServers()

        lblTodo.Text = My.Computer.FileSystem.ReadAllText("Todo.txt")

        dtMissionsList.TableName = "Missions"
        Dim c As New DataColumn
        c.ColumnName = "Mission Name"
        dtMissionsList.Columns.Add(c)

        Dim c1 As New DataColumn
        c1.ColumnName = "Param 1"
        dtMissionsList.Columns.Add(c1)

        Dim c2 As New DataColumn
        c2.ColumnName = "Param 2"
        dtMissionsList.Columns.Add(c2)

        Dim c3 As New DataColumn
        c3.ColumnName = "Difficulty"
        dtMissionsList.Columns.Add(c3)

        For i = 0 To 25
            Me.cbxParam1.Items.Add(i)
            Me.cbxParam2.Items.Add(i)
        Next
        For i = 0 To 32
            Me.cbxMaxPlayers.Items.Add(i)
        Next

        'RefreshMissionsCbx()
    End Sub

    Private Sub GetServers()
        Dim blnOpenDialog As Boolean = False
        If File.Exists(FileLocation) Then
            'dsServerList.ReadXml(Application.StartupPath & "servers.xml")
            Try
                dtServerList.Clear()
                dtServerList.ReadXml(FileLocation)
                If dtServerList.Tables.Count > 0 Then
                    If dtServerList.Tables(0).Rows.Count > 0 Then
                        'Clear the combobox
                        Dim dtClear As New DataTable
                        ComboBox1.DataSource = dtClear
                        ComboBox1.Refresh()

                        'Refresh data into box
                        ComboBox1.DataSource = dtServerList.Tables(0)
                        If dtServerList.Tables(0).Rows.Count <> 0 Then
                            ComboBox1.DisplayMember = "Server Name"
                            ComboBox1.ValueMember = "Web Service Location"
                            ComboBox1.Refresh()
                        End If
                        'blnOpenDialog = True
                    Else
                        blnOpenDialog = True
                    End If
                Else
                    blnOpenDialog = True
                End If
            Catch ex As Exception

            End Try
            If blnOpenDialog Then
                Dim f As New frmEditServers
                f.ShowDialog()
                If f.DialogResult = Windows.Forms.DialogResult.No Then
                    dtServerList.ReadXml(FileLocation)
                    If dtServerList.Tables(0).Rows.Count = 0 Then

                    End If
                    Me.Close()
                End If
                GetServers()
            End If
        Else
            Dim f As New frmEditServers
            f.ShowDialog()
            GetServers()
            If f.DialogResult = Windows.Forms.DialogResult.Cancel Then
                Me.Close()
            End If
        End If
    End Sub

    Private Function ServerConnect() As Boolean
        Try
            'Verify client and web service version
            Dim ServiceVersion As String = oWS.VersionVerify
            Dim svrMessage As String = ""
            If ServiceVersion <> Version Then
                svrMessage = "Server Version: " & ServiceVersion & vbNewLine & "Client Version: " & Version & vbNewLine & vbNewLine & "Version do not match. Cannot connect"
                MsgBox(svrMessage, MsgBoxStyle.Critical, "Version Mismatch")
                Return False
            End If
            Return True
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical, ex.Message)
            Return False
        End Try

    End Function

    Private Sub tmrMaintenance_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrMaintenance.Tick
        If txbNewMission.Text <> "" Then
            btnNewMissionUpload.Enabled = True
        Else
            btnNewMissionUpload.Enabled = False
        End If


        If Me.ListMissionsBox.SelectedIndex <> -1 And Me.ListMissionsBox.SelectedItem <> "No Missions" Then
            Me.DeleteToolStripMenuItem.Visible = True
        Else
            Me.DeleteToolStripMenuItem.Visible = False
        End If

        If Me.txbAdminPassword.Text = "" Then Me.btnSettingsSet.Enabled = False Else Me.btnSettingsSet.Enabled = True

        If dgvUsers.SelectedRows.Count > 0 Then
            btnEditUser.Enabled = True
            btnDeleteUser.Enabled = True
            btnResetPassword.Enabled = True
        Else
            btnEditUser.Enabled = False
            btnDeleteUser.Enabled = False
            btnResetPassword.Enabled = False
        End If

        'change things based on Arma Version
        If ArmaVersion = "ARMA2" Then
            PictureBox1.Image = My.Resources.ARMA2_logo
            Label6.Visible = False
            Label7.Visible = False
            cbxParam1.Visible = False
            cbxParam2.Visible = False

            cbxMode.Items.Clear()
            cbxMode.Items.Add("Recruit")
            cbxMode.Items.Add("Regular")
            cbxMode.Items.Add("Veteran")
            cbxMode.Items.Add("Mercenary")
        Else
            PictureBox1.Image = My.Resources.news_pic_update114

            Label6.Visible = True
            Label7.Visible = True
            cbxParam1.Visible = True
            cbxParam2.Visible = True

            cbxMode.Items.Clear()
            cbxMode.Items.Add("Cadet")
            cbxMode.Items.Add("Veteran")
        End If

        TabControl1.Enabled = boolConnected
    End Sub

    Public Sub doFileUploadViaWebService(ByVal oFileInfo As FileInfo)
        Dim oFile As File                     'File object
        Dim oFileStream As FileStream = Nothing         'Holds the Stream of the File

        'Dim oWS As New ArmaWebService   'the webservice 

        Dim strReturn As String = ""                    'Value returned from the webservice
        Dim bolResult As Boolean = False                'Result returned from the webservice

        Try
            'Make sure that the file exists before trying to upload
            If File.Exists(oFileInfo.FullName) = False Then Exit Sub

            'Open the file and break it down into a file stream
            oFileStream = File.Open(oFileInfo.FullName, IO.FileMode.Open, IO.FileAccess.Read)

            'declare the byte array of the file
            Dim oFileByte(oFileStream.Length - 1) As Byte

            'break the file into bytes and place into the byte object
            oFileStream.Read(oFileByte, 0, oFileStream.Length)

            'upload the file to the webservice
            bolResult = oWS.UploadFile(des.Encrypt(UserName), Password, oFileInfo.Name, oFileByte, strReturn)

            'display the results
            If bolResult = False Then
                Throw New Exception(strReturn)
            Else
                'report progress and close window
                bwpUploadFile.ReportProgress(100, "Complete")
                'MsgBox("File Uploaded Successfully")
            End If

        Catch ex As Exception
            'display errors
            bwpUploadFile.ReportProgress(100, "Error: " & ex.Message.ToString)
            '            MsgBox(ex.Message.ToString)
        Finally
            'cleanup
            'oWS = Nothing
            oFile = Nothing
            oFileStream.Close()
        End Try
    End Sub

    Private Sub btnNewMissionBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewMissionBrowse.Click
        Me.OpenFileDialog1.ShowDialog()
        Me.txbNewMission.Text = Me.OpenFileDialog1.FileName
    End Sub

    Private Sub btnNewMissionUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewMissionUpload.Click
        'open the window to say that it is uploading
        If Not bwpUploadFile.IsBusy Then
            bwpUploadFile.RunWorkerAsync()
            frmUpload = New frmUploading
            frmUpload.ShowDialog(Me)
        End If
        'Dim UploadMe As New FileInfo(Me.txbNewMission.Text)
        'Me.doFileUploadViaWebService(UploadMe)

    End Sub

    Private Sub tmrServerStatus_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrServerStatus.Tick
        If Me.bwpServerStatus.IsBusy = False And boolConnected = True Then
            Me.bwpServerStatus.RunWorkerAsync()
        End If

        If Me.bwpTSServerStatus.IsBusy = False And boolConnected = True Then
            Me.bwpTSServerStatus.RunWorkerAsync()
        End If

    End Sub

    Private Sub bwpServerStatus_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwpServerStatus.DoWork
        ServerStatus()
    End Sub

    Private Sub bwpTSServerStatus_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwpTSServerStatus.DoWork
        TSServerStatus()
    End Sub

    Private Sub bwpServerStatus_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwpServerStatus.ProgressChanged
        Me.txbStatus.Text = e.UserState
        If e.UserState = "RUNNING" Then
            Me.txbStatus.BackColor = Color.Green
            Me.btnStartServer.Enabled = False
            Me.btnStopServer.Enabled = True
        Else
            Me.txbStatus.BackColor = Color.Red
            Me.btnStartServer.Enabled = True
            Me.btnStopServer.Enabled = False
        End If
    End Sub

    Private Sub bwpTSServerStatus_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwpTSServerStatus.ProgressChanged
        Me.txbTSStatus.Text = e.UserState
        If e.UserState = "RUNNING" Then
            Me.txbTSStatus.BackColor = Color.Green
            Me.btnStartTSServer.Enabled = False
            Me.btnStopTSServer.Enabled = True
        Else
            Me.txbTSStatus.BackColor = Color.Red
            Me.btnStartTSServer.Enabled = True
            Me.btnStopTSServer.Enabled = False
        End If
    End Sub

    Private Sub ServerStatus()
        'Dim oWS As New ArmaWebService
        Try
            Dim aReturn As String() = oWS.ServerStatus(des.Encrypt(UserName), Password)
            If aReturn(0) = True Then
                'Me.txbStatus.BackColor = Color.Green
                Me.bwpServerStatus.ReportProgress(0, "RUNNING")
            Else
                'Me.txbStatus.BackColor = Color.Red
                Me.bwpServerStatus.ReportProgress(0, "NOT RUNNING")
            End If
            'boolConnected = True
        Catch ex As Exception
            'boolConnected = False
        End Try

    End Sub

    Private Sub TSServerStatus()
        'Dim oWS As New ArmaWebService
        Try
            Dim aReturn As String() = oWS.ServerTSStatus(des.Encrypt(UserName), Password)
            If aReturn(0) = True Then
                'Me.txbStatus.BackColor = Color.Green
                Me.bwpTSServerStatus.ReportProgress(0, "RUNNING")
            Else
                'Me.txbStatus.BackColor = Color.Red
                Me.bwpTSServerStatus.ReportProgress(0, "NOT RUNNING")
            End If
            'boolConnected = True
        Catch ex As Exception
            'boolConnected = False
        End Try

    End Sub

    Private Sub nonbwpServerStatus()
        'Dim oWS As New ArmaWebService
        Try
            Dim aReturn As String() = oWS.ServerStatus(des.Encrypt(UserName), Password)
            If aReturn(0) = True Then
                Me.txbStatus.Text = "RUNNING"
                Me.txbStatus.BackColor = Color.Green
                Me.btnStartServer.Enabled = False
                Me.btnStopServer.Enabled = True
            Else
                Me.txbStatus.Text = "NOT RUNNING"
                Me.txbStatus.BackColor = Color.Red
                Me.btnStartServer.Enabled = True
                Me.btnStopServer.Enabled = False
            End If
            'boolConnected = True
        Catch ex As Exception
            'boolConnected = False
        End Try

    End Sub

    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefreshToolStripMenuItem.Click
        Dim output As String() = oWS.ShowMissions(des.Encrypt(UserName), Password)
        Dim s As String = Nothing
        Me.ListMissionsBox.Items.Clear()
        For Each s In output
            If Path.GetExtension(s).ToUpper = ".PBO" Then
                Me.ListMissionsBox.Items.Add(Path.GetFileNameWithoutExtension(s))
            End If
        Next
    End Sub

    Private Sub btnStartServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartServer.Click
        Dim StartServer As String = oWS.StartServer(des.Encrypt(UserName), Password)
        If StartServer <> "Success" Then
            MsgBox("Error During Startup" & vbNewLine & StartServer)
        End If
    End Sub

    Private Sub btnStopServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopServer.Click
        oWS.StopServer(des.Encrypt(UserName), Password)
    End Sub

    Private Sub DeleteToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripMenuItem.Click
        If Me.ListMissionsBox.SelectedIndex <> -1 And Me.ListMissionsBox.SelectedItem <> "No Missions" Then
            If MsgBox("Do you wish to delete '" & Me.ListMissionsBox.SelectedItem & "'?", MsgBoxStyle.YesNo, "Delete Mission") = MsgBoxResult.Yes Then
                If oWS.DeleteMission(des.Encrypt(UserName), Password, Me.ListMissionsBox.SelectedItem) Then
                    MsgBox("Mission " & Me.ListMissionsBox.SelectedItem & " deleted")
                End If
            End If
        End If
        Dim output As String() = oWS.ShowMissions(des.Encrypt(UserName), Password)
        Dim s As String = Nothing
        Me.ListMissionsBox.Items.Clear()
        For Each s In output
            If Path.GetExtension(s).ToUpper = ".PBO" Then
                Me.ListMissionsBox.Items.Add(Path.GetFileNameWithoutExtension(s))
            End If
        Next
    End Sub

    Private Sub btnSettingsTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettingsSet.Click
        Dim dsSettings As New DataSet
        Dim dtSettings As New DataTable
        dtSettings.TableName = "ConfigSettings"
        dtSettings.Columns.Add("Password", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("AdminPassword", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("Mode", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("Mission", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("Param1", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("Param2", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("ServerName", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("Persistent", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("MaxPlayers", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("MOTD", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("MODS", System.Type.GetType("System.String"))
        dtSettings.Columns.Add("PORT", System.Type.GetType("System.String"))

        Dim r As DataRow = dtSettings.NewRow()
        r(0) = txbPassword.Text
        r(1) = txbAdminPassword.Text
        r(2) = cbxMode.SelectedItem
        r(3) = cbxMission.SelectedItem
        r(4) = cbxParam1.SelectedItem
        r(5) = cbxParam2.SelectedItem
        r(6) = txbServerName.Text
        r(7) = cbxPersistent.Checked
        r(8) = cbxMaxPlayers.SelectedItem
        r(9) = Replace(Me.txbMOTD.Text, vbCrLf, "|")
        r(10) = txbMods.Text
        r(11) = txbPort.Text

        dtSettings.Rows.Add(r)
        dsSettings.Tables.Add(dtSettings)

        'Dim dtMission As New DataTable
        'dtMission.TableName = "Missions"
        'For Each r1 As DataRow In dtMissionsList.Rows
        '    dtMission.Rows.Add(r1)
        'Next

        dsSettings.Tables.Add(dtMissionsList.Copy())

        If oWS.SaveSettingsXML(des.Encrypt(UserName), Password, dsSettings) Then
            File.Delete(SettingsFile)
            MsgBox("Settings have been updated. Restart server for them to take effect.", MsgBoxStyle.Information, "Settings Updated")
        Else
            MsgBox("Error during save.")
        End If


    End Sub

    Private Sub btnGetConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetConfig.Click
        ' File.Delete(SettingsFile)
        RefreshMissionsCbx()
        cbxParam1.SelectedIndex = 0
        cbxParam2.SelectedIndex = 0
        cbxMode.SelectedIndex = 1
        Try
            Dim dsSettings As New DataSet
            dsSettings = oWS.GetSettingsXML(des.Encrypt(UserName), Password)

            With dsSettings.Tables("ConfigSettings").Rows(0)
                Me.txbPassword.Text = .Item("Password")
                Me.txbAdminPassword.Text = .Item("AdminPassword")
                'Me.cbxMode.SelectedItem = .Item("Mode")
                'Me.cbxMission.SelectedItem = .Item("Mission")
                'Me.cbxParam1.SelectedItem = CInt(.Item("Param1"))
                'Me.cbxParam2.SelectedItem = CInt(.Item("Param2"))
                Me.txbServerName.Text = .Item("ServerName")
                Me.cbxPersistent.Checked = CBool(.Item("Persistent"))
                Me.cbxMaxPlayers.SelectedItem = CInt(.Item("MaxPlayers"))
                Me.txbMOTD.Text = Replace(.Item("MOTD"), "|", vbCrLf)
                Me.txbMods.Text = .Item("MODS")
                Me.txbPort.Text = .Item("PORT")
            End With

            If dsSettings.Tables("Missions") IsNot Nothing Then
                dtMissionsList = dsSettings.Tables("Missions")
                If dtMissionsList.Rows.Count > 0 Then
                    RefreshMissionGrid(dtMissionsList)
                Else
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub RefreshMissionGrid(ByVal dtTable As DataTable)
        dgMissions.DataSource = dtTable
        dgMissions.Refresh()
        'dgMissions.Rows.Clear()
        'For Each r As DataRow In dtTable.Rows
        '    dgMissions.Rows.Add(r)
        'Next
        'dgMissions.Refresh()
    End Sub

    Private Sub Label8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label8.Click
        RefreshMissionsCbx()
    End Sub

    Private Sub RefreshMissionsCbx()
        Dim output As String() = oWS.ShowMissions(des.Encrypt(UserName), Password)
        Dim s As String = Nothing
        Me.cbxMission.Items.Clear()
        For Each s In output
            If Path.GetExtension(s).ToUpper = ".PBO" Then
                Me.cbxMission.Items.Add(Path.GetFileNameWithoutExtension(s))
            End If
        Next
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditServers.Click
        Dim dtClear As New DataTable
        ComboBox1.DataSource = dtClear
        ComboBox1.Refresh()
        Dim f As New frmEditServers
        f.ShowDialog()
        GetServers()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click


        'oWS.Url =
        Try
            oWS.Url = ComboBox1.SelectedValue
            oWS = oWS

            'If ServerConnect() = False Then
            '    Exit Sub
            'End If

            Login()

            SetUserLevelOptions(UserLevel)
            tmrSlowMaintenance.Enabled = True
            nonbwpServerStatus()
            tmrMaintenance.Enabled = True
            tmrServerStatus.Enabled = True
        Catch ex As Exception
            tmrMaintenance.Enabled = False
            tmrServerStatus.Enabled = False
        End Try



        'If ToolStripComboBox1.SelectedItem = "ArmA 1" Then
        '    oWS = oWS
        '    Server = 1
        'ElseIf ToolStripComboBox1.SelectedItem = "ArmA 2" Then
        '    oWS = oWS2
        '    Server = 2
        'End If


    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        lbxBan.Items.Clear()

        Dim arrList As String() = Split(oWS.BanGetList(des.Encrypt(UserName), Password), "||")

        For Each s In arrList
            If Trim(s) <> "" Then
                lbxBan.Items.Add(s)
            End If
        Next

    End Sub

    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
        If lbxBan.SelectedItems.Count > 0 Then
            MsgBox(oWS.BanRemoveUser(des.Encrypt(UserName), Password, lbxBan.SelectedItems.Item(0)), MsgBoxStyle.Information, "Unban User")
            Me.ToolStripMenuItem1.PerformClick()
        Else
            MsgBox("Select a user", MsgBoxStyle.Critical, "Unban User")
        End If

    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox(oWS.BanAddUser(des.Encrypt(UserName), Password, txbBanUser.Text), MsgBoxStyle.Information, "Ban user")
        Me.ToolStripMenuItem1.PerformClick()
    End Sub

    Private Sub Login()
        Dim l As New frmLogin
        l.ShowDialog()
        Select Case l.DialogResult
            Case Windows.Forms.DialogResult.No
                If strike < 2 Then
                    strike += 1
                    MsgBox("Incorrect Login." & vbNewLine & (3 - strike) & " Logins attempt left.", MsgBoxStyle.Critical, "Failed Login")
                    Login()
                Else
                    MsgBox("Incorrect Login. Attempt has been logged with IP and user information.", MsgBoxStyle.Critical, "Failed Login")
                    Me.Close()
                End If
            Case Windows.Forms.DialogResult.Cancel
                Me.Close()
            Case Windows.Forms.DialogResult.OK
                ArmaVersion = oWS.ArmaVersion()
                Exit Sub
            Case Else
                Me.Close()
        End Select
    End Sub

    Private Sub btnAddMission_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddMission.Click
        Dim r As DataRow = dtMissionsList.NewRow
        r.Item("Mission Name") = cbxMission.Text
        r.Item("Param 1") = cbxParam1.Text
        r.Item("Param 2") = cbxParam2.Text
        r.Item("Difficulty") = cbxMode.Text
        dtMissionsList.Rows.Add(r)
        RefreshMissionGrid(dtMissionsList)
    End Sub

    Private Sub SetUserLevelOptions(ByVal AdminLevel As Integer)
        'If UserName = "captain" Then AdminLevel = 4

        If AdminLevel = -2 Then
            MsgBox("Your administrative level is too low. Program is now closing", MsgBoxStyle.Critical, "Closing Program")
            Me.Close()
        ElseIf AdminLevel = -1 Then
            'Level -1 allows only user creation abilities
            TabControl1.SelectTab(4)
            pnlServer.Enabled = False
            pnlConfig.Enabled = False
            pnlMissions.Enabled = False
            pnlBanList.Enabled = False
            pnlSecurity.Enabled = True
            boolConnected = True

            pnlConfig.Visible = False
            pnlMissions.Visible = False
            pnlBanList.Visible = False
            pnlSecurity.Visible = True
        ElseIf AdminLevel = 0 Then
            'Level 0 allows only view options
            pnlServer.Enabled = False
            pnlConfig.Enabled = False
            pnlMissions.Enabled = False
            pnlBanList.Enabled = False
            pnlSecurity.Enabled = False
            boolConnected = True

            pnlConfig.Visible = False
            pnlMissions.Visible = False
            pnlBanList.Visible = False
            pnlSecurity.Visible = False
        ElseIf AdminLevel = 1 Then
            'Level 1 allows server restart
            pnlServer.Enabled = True
            pnlConfig.Enabled = False
            pnlMissions.Enabled = False
            pnlBanList.Enabled = False
            pnlSecurity.Enabled = False
            boolConnected = True

            pnlConfig.Visible = False
            pnlMissions.Visible = False
            pnlBanList.Visible = False
            pnlSecurity.Visible = False
        ElseIf AdminLevel = 2 Then
            'level 2 allows banning
            pnlServer.Enabled = True
            pnlConfig.Enabled = False
            pnlMissions.Enabled = False
            pnlBanList.Enabled = True
            pnlSecurity.Enabled = False
            boolConnected = True

            pnlConfig.Visible = False
            pnlMissions.Visible = False
            pnlBanList.Visible = True
            pnlSecurity.Visible = False
        ElseIf AdminLevel = 3 Then
            'level 3 allows mission adding, config modifying
            pnlServer.Enabled = True
            pnlConfig.Enabled = True
            pnlMissions.Enabled = True
            pnlBanList.Enabled = True
            pnlSecurity.Enabled = False
            boolConnected = True

            pnlConfig.Visible = True
            pnlMissions.Visible = True
            pnlBanList.Visible = True
            pnlSecurity.Visible = False
        ElseIf AdminLevel = 4 Then
            'level 4 allows user editing
            pnlServer.Enabled = True
            pnlConfig.Enabled = True
            pnlMissions.Enabled = True
            pnlBanList.Enabled = True
            pnlSecurity.Enabled = True
            boolConnected = True

            pnlConfig.Visible = True
            pnlMissions.Visible = True
            pnlBanList.Visible = True
            pnlSecurity.Visible = True
        End If

        '        pnlServer.Visible = pnlServer.Enabled
        'pnlConfig.Visible = pnlConfig.Enabled
        'pnlMissions.Visible = pnlMissions.Enabled
        'pnlBanList.Visible = pnlBanList.Enabled
        'pnlSecurity.Visible = pnlSecurity.Enabled

        Dim output As String() = oWS.ShowMissions(des.Encrypt(UserName), Password)
        Dim s As String = Nothing
        Me.ListMissionsBox.Items.Clear()
        For Each s In output
            If Path.GetExtension(s).ToUpper = ".PBO" Then
                Me.ListMissionsBox.Items.Add(Path.GetFileNameWithoutExtension(s))
            End If
        Next

    End Sub
    Enum MsgType
        MsgByte
        MsgString
    End Enum

    Private Sub UpdateQueryLog(ByVal NewMessage As Object, Optional ByVal MsgType As MsgType = MsgType.MsgString)
        Select Case MsgType
            Case Form1.MsgType.MsgByte
                Dim BitDet As Byte() = NewMessage
                Dim tempStr2 As String = ""
                Dim tempStr As String = ""
                Dim i As Int16 = 0
                Dim line As Int16 = 0
                Dim result As String = ""
                For j = 0 To BitDet.Length - 1
                    If BitDet(j) = True Then
                        Console.Write("1 ")
                        tempStr2 = tempStr
                        tempStr = " 1" + tempStr2
                    Else
                        Console.Write("0 ")
                        tempStr2 = tempStr
                        tempStr = " 0" + tempStr2
                    End If
                    i += 1
                    If i = 8 And j <= (BitDet.Length - 1) Then
                        line += 1
                        i = 0
                        result = result + tempStr
                        tempStr = ""
                        tempStr2 = ""
                        result = result + vbCrLf
                        If j <> (BitDet.Length - 1) Then
                            result = result + line.ToString & ") "
                            txbQryLog.Text = FormatDateTime(Now, DateFormat.ShortDate) & result & vbNewLine & txbQryLog.Text
                        End If
                    End If
                Next
            Case Else

        End Select
        txbQryLog.Text = FormatDateTime(Now, DateFormat.ShortDate) & NewMessage & vbNewLine & txbQryLog.Text
    End Sub

    Public Sub ReceiveMessages()
        Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
        'txtIP.Text = RemoteIpEndPoint.Address.ToString
        Dim BitDet As BitArray
        BitDet = New BitArray(receiveBytes)
        Dim strReturnData As String = _
                    System.Text.Encoding.Unicode.GetString(receiveBytes)
        UpdateQueryLog(strReturnData, MsgType.MsgByte)
    End Sub



    Private Sub btnServerQuery_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnServerQuery.Click
        Try
            btnGetConfig.PerformClick()

            'Dim intPort As Integer = txbPort.Text
            'If intPort = "" Then MsgBox("Please update the config page and try again") : Exit Sub

            Dim udpClient As New UdpClient

            Dim GLOIP As IPAddress = IPAddress.Parse(txbQryIP.Text)
            Dim GLOINTPORT As Integer = txbQryPort.Text
            Dim bytCommand As Byte() = New Byte() {}

            udpClient.Close()
            udpClient.Connect(GLOIP, GLOINTPORT)
            bytCommand = Encoding.ASCII.GetBytes(";þý.CORYÿÿ.")
            Dim pRet As Integer = udpClient.Send(bytCommand, bytCommand.Length)
            UpdateQueryLog("No of bytes send " & pRet)


            'receive the reply
            SocketNO = CInt(txbQryPort.Text)
            receivingUdpClient = New System.Net.Sockets.UdpClient(SocketNO)
            ThreadReceive = _
               New System.Threading.Thread(AddressOf ReceiveMessages)
            ThreadReceive.Start()



        Catch ex As Exception
            UpdateQueryLog(ex.Message)
        End Try


        '$addr="ip.adress"; // e.g: 127.0.0.1
        '$port="port"; // e.g: 2302

        '$sock = fsockopen(("udp://" . $addr),$port,$errno,$errdesc,$maxwait);
        '$query = pack("c*",0xfe,0xfd,0x00,0x04,0x05,0x06,0x07,0xff,0xff,0xff);

        'fwrite($sock,$query);
        '@socket_set_timeout($sock, 2);
        '$reply = @fread($sock, 2048);
        '  fclose($sock);

        'if($reply != '')
        '{
        '$infoarray = explode(chr(0), $reply);

        '$querysuccess = true;
        '$name = $infoarray[4];
        '$ver = $infoarray[2];
        '$status = $infoarray[16];
        '$numteams = $infoarray[12];
        '$numplayers = $infoarray[10];
        '$maxplayers = $infoarray[14];
        '$gametype = $infoarray[8];
        '$mission = $infoarray[44];
        '$players = $infoarray[54] . $infoarray[58] . $infoarray[62]; // and so on and so on (interval of 4 per player)
        '};


        'Dim client1 As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        'Dim server1 As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        ''Dim MyIP As IPAddress

        'Dim str As String
        'Dim bytes1(200) As Byte
        'Dim bytes2(200) As Byte
        'Dim Port1 As Integer = 23002
        'Dim port2 As Integer = 2048

        ''MyIP = IPAddress.Parse("24.96.101.10")
        'Dim server2 As New IPEndPoint(IPAddress.Parse("24.96.101.10"), Port1)
        'Dim client2 As New IPEndPoint(IPAddress.Parse("24.96.101.10"), port2)
        'client1.Bind(client2)

        'Try
        '    str = "asdf"
        '    bytes1 = Encoding.ASCII.GetBytes(str)
        '    client1.SendTo(bytes1, server2)

        '    client1.ReceiveFrom(bytes2, server2)
        'Catch ex As Exception
        'End Try
        'client1.Close()
    End Sub

    Private Sub tmrSlowMaintenance_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrSlowMaintenance.Tick
        SetUserLevelOptions(UserLevel)
    End Sub

    Private Sub btnAddUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddUser.Click
        If txbUsername.Text = "" Then MsgBox("Please enter a name", MsgBoxStyle.Exclamation, "Incomplete Form") : Exit Sub
        If txbUserPassword.Text = "" Then MsgBox("Please enter a password", MsgBoxStyle.Exclamation, "Incomplete Form") : Exit Sub
        If cbxAdminLevel.SelectedIndex = -1 Then MsgBox("Please select an admin level", MsgBoxStyle.Exclamation, "Incomplete Form") : Exit Sub
        'If txbUsername.Text = "" Then MsgBox("Please enter a name", MsgBoxStyle.MsgBoxHelp, "Incomplete Form") : Exit Sub
        MsgBox(oWS.ModifyUser(des.Encrypt(UserName), Password, des.Encrypt("AddUser"), des.Encrypt(txbUsername.Text), des.Encrypt(txbUserPassword.Text), _
                     des.Encrypt(cbxAdminLevel.SelectedItem.ToString), des.Encrypt(dtpAdminFrom.Value), des.Encrypt(dtpAdminTo.Value)), MsgBoxStyle.Information, "User Modified")
        tsbRefresh.PerformClick()
    End Sub

    Private Sub RefreshToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbRefresh.Click
        Dim dtClear As New DataTable
        dgvUsers.DataSource = dtClear
        dgvUsers.Refresh()

        Dim dtTable = oWS.GetUsers(des.Encrypt(UserName), Password)
        dgvUsers.DataSource = dtTable
        If dtTable IsNot Nothing Then
            For Each r As DataRow In dtTable.Rows
                r.Item("password") = "********"
            Next

            dgvUsers.Refresh()

            dgvUsers.Columns(0).HeaderText = "User Name"
            dgvUsers.Columns(0).ReadOnly = True
            dgvUsers.Columns(1).HeaderText = "Password"
            dgvUsers.Columns(1).ReadOnly = True
            dgvUsers.Columns(2).HeaderText = "Admin Level"
            dgvUsers.Columns(3).HeaderText = "Starting Date"
            dgvUsers.Columns(4).HeaderText = "Ending Date"
        End If

    End Sub

    Private Sub btnResetPassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResetPassword.Click
        Dim f As New frmResetPassword
        f.ShowDialog()
        If f.DialogResult = Windows.Forms.DialogResult.OK Then
            'reset the users password
            Dim usrPassword As String = f.txbNewPass.Text
            Dim rI As Integer = dgvUsers.SelectedRows(0).Index
            MsgBox(oWS.ModifyUser(des.Encrypt(UserName), Password, des.Encrypt("EditUser"), des.Encrypt(dgvUsers.Item(0, rI).Value), des.Encrypt(usrPassword), _
                           des.Encrypt(dgvUsers.Item(2, rI).Value), des.Encrypt(dgvUsers.Item(3, rI).Value), des.Encrypt(dgvUsers.Item(4, rI).Value)), MsgBoxStyle.Information, "User Password")
        End If
        tsbRefresh.PerformClick()
    End Sub

    Private Sub btnEditUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditUser.Click

        Try
            Dim f As New frmEditUser
            Dim rI As Integer = dgvUsers.SelectedRows(0).Index
            If f.cbxAdminLevel.SelectedItem Is Nothing Then
                f.cbxAdminLevel.SelectedIndex = 1
            End If
            f.txbUsername.Text = dgvUsers.Item(0, rI).Value
            f.cbxAdminLevel.SelectedItem = dgvUsers.Item(2, rI).Value
            f.dtpAdminFrom.Value = dgvUsers.Item(3, rI).Value
            f.dtpAdminTo.Value = dgvUsers.Item(4, rI).Value
            f.ShowDialog()
            If f.DialogResult = Windows.Forms.DialogResult.OK Then
                'Dim rI As Integer = dgvUsers.SelectedRows(0).Index
                MsgBox(oWS.ModifyUser(des.Encrypt(UserName), Password, des.Encrypt("EditUser"), des.Encrypt(f.txbUsername.Text), des.Encrypt("$//NONE\\$"), _
                               des.Encrypt(f.cbxAdminLevel.SelectedItem), des.Encrypt(f.dtpAdminFrom.Value), des.Encrypt(f.dtpAdminTo.Value)), MsgBoxStyle.Information, "Edit User")

            End If
        Catch ex As Exception

        End Try
        tsbRefresh.PerformClick()
    End Sub

    Private Sub btnDeleteUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteUser.Click
        Dim rI As Integer = dgvUsers.SelectedRows(0).Index
        If MsgBox("Are you sure you want to delete user '" & dgvUsers.Item(0, rI).Value & "'?", MsgBoxStyle.YesNo, "Delete User") = MsgBoxResult.Yes Then
            MsgBox(oWS.ModifyUser(des.Encrypt(UserName), Password, des.Encrypt("DeleteUser"), des.Encrypt(dgvUsers.Item(0, rI).Value), des.Encrypt("$//NONE\\$"), _
                                       des.Encrypt(dgvUsers.Item(2, rI).Value), des.Encrypt(dgvUsers.Item(3, rI).Value), des.Encrypt(dgvUsers.Item(4, rI).Value)), MsgBoxStyle.Information, "Delete User")
        End If
        tsbRefresh.PerformClick()
    End Sub

    Private Sub btnStartTSServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartTSServer.Click
        Dim StartTSServer As String = oWS.StartTSServer(des.Encrypt(UserName), Password)
        If StartTSServer <> "Success" Then
            MsgBox("Error During Startup" & vbNewLine & StartTSServer)
        End If
    End Sub

    Private Sub btnStopTSServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopTSServer.Click
        oWS.StopTSServer(des.Encrypt(UserName), Password)
    End Sub

    Private Sub bwpUploadFile_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwpUploadFile.DoWork
        Dim UploadMe As New FileInfo(Me.txbNewMission.Text)
        Me.doFileUploadViaWebService(UploadMe)
    End Sub

    Private Sub bwpUploadFile_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwpUploadFile.ProgressChanged
        If e.ProgressPercentage = 100 Then
            'end the process and close the window
            frmUpload.Close()
            If e.UserState <> "Complete" Then
                MsgBox(e.UserState.ToString, MsgBoxStyle.Critical, "Error")
            End If
        End If
    End Sub

    Private Sub bwpUploadFile_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwpUploadFile.RunWorkerCompleted
        frmUpload.Close()
        Dim output As String() = oWS.ShowMissions(des.Encrypt(UserName), Password)
        Dim s As String = Nothing
        Me.ListMissionsBox.Items.Clear()
        For Each s In output
            If Path.GetExtension(s).ToUpper = ".PBO" Then
                Me.ListMissionsBox.Items.Add(Path.GetFileNameWithoutExtension(s))
            End If
        Next
    End Sub

    Private Sub btnRefreshLogs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefreshLogs.Click
        Try
            rtbLogData.Text = oWS.GetLogs(cbxLogFiles.SelectedItem)
        Catch ex As Exception
            rtbLogData.Text = ex.ToString
        End Try
    End Sub
End Class

